<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名称" prop="fileName">
        <el-input
            v-model="queryParams.fileName"
            placeholder="请输入文件名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件类型" prop="fileType">
        <el-select v-model="queryParams.fileType" placeholder="请选择文件类型" clearable>
          <el-option
              v-for="dict in file_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['sources:surResourceDetail:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['sources:surResourceDetail:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['sources:surResourceDetail:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="surResourceDetailList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" fixed="left" align="center"/>
      <el-table-column label="文件名称" align="center" fixed="left" min-width="180" show-overflow-tooltip prop="fileName"/>
      <el-table-column label="文件路径" align="center" min-width="180" show-overflow-tooltip prop="filePath"/>
      <el-table-column label="文件类型" align="center" min-width="120" prop="fileType">
        <template #default="scope">
          <dict-tag :options="file_type" :value="scope.row.fileType"/>
        </template>
      </el-table-column>
      <el-table-column label="文件大小 " align="center" min-width="140" prop="fileSize">
        <template #default="scope">
          <span>{{ convertFileSize(scope.row.fileSize) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="文件描述" align="center" min-width="100" show-overflow-tooltip prop="fileDesc"/>
      <el-table-column label="会员专享 " align="center" min-width="120" prop="memberVip">
        <template #default="scope">
          <tc-status :status="scope.row.memberVip" :format="['否', '是']"/>
        </template>
      </el-table-column>
      <el-table-column label="是否收费" align="center" min-width="120" prop="chargeStatus">
        <template #default="scope">
          <tc-status :status="scope.row.memberVip" :format="['否', '是']"/>
        </template>
      </el-table-column>
      <el-table-column label="单价" align="center" min-width="160" prop="filePrice"/>
      <el-table-column label="文件状态" align="center" min-width="120" prop="fileStatus">
        <template #default="scope">
          <tc-status :status="scope.row.fileStatus" :format="['正常', '禁用']"/>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" min-width="80" prop="fileSort"/>
      <el-table-column label="操作" align="center" width="180" fixed="right" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              type="text"
              icon="View"
              @click="handleView(scope.row)"
              v-hasPermi="['sources:surResourceDetail:view']"
          >预览
          </el-button>
          <el-button
              type="text"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['sources:surResourceDetail:edit']"
          >修改
          </el-button>
          <el-button
              type="text"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['sources:surResourceDetail:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改资源明细对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" :close-on-click-modal="false" append-to-body>
      <el-form ref="surResourceDetailRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件" prop="filePath">
          <file-upload v-model="form.filePath" @change="handleFileChange" :limit="1" auth="Y"/>
        </el-form-item>
        <el-form-item label="文件名称" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入文件名称"/>
        </el-form-item>
<!--        <el-form-item label="文件类型" prop="fileType">
          <el-select v-model="form.fileType" placeholder="请选择文件类型">
            <el-option
                v-for="dict in file_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item label="文件大小 " prop="fileSize">
          <el-input v-model="form.fileSize" disabled placeholder="请输入文件大小 "/>
        </el-form-item>
        <el-form-item label="会员专享 " prop="memberVip">
          <el-switch v-model="form.memberVip" :active-value="1" :inactive-value="0"/>
        </el-form-item>
        <el-form-item label="是否收费 " prop="chargeStatus">
          <el-switch v-model="form.chargeStatus" :active-value="1" :inactive-value="0"/>
        </el-form-item>
        <el-form-item v-if="form.chargeStatus === 1" label="单价" prop="filePrice">
          <el-input-number v-model="form.filePrice" controls-position="right" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="是否禁用" prop="fileStatus">
          <el-switch v-model="form.fileStatus" :active-value="1" :inactive-value="0"/>
        </el-form-item>
        <el-form-item label="文件排序" prop="fileSort">
          <el-input-number v-model="form.fileSort" controls-position="right" :min="0" :precision="0" />
        </el-form-item>
        <el-form-item label="文件描述" prop="fileDesc">
          <el-input type="textarea" v-model="form.fileDesc" placeholder="请输入文件描述"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SurResourceDetail">
import TcStatus from "@/components/TcStatus/index.vue";
import {
  listSurResourceDetail,
  getSurResourceDetail,
  delSurResourceDetail,
  addSurResourceDetail,
  updateSurResourceDetail
} from "@/api/sources/surResourceDetail";
import FileUpload from "@/components/FileUpload/index.vue";

const {proxy} = getCurrentInstance();
const {file_type} = proxy.useDict('file_type');

const props = defineProps({
  resourceId: String
})

const surResourceDetailList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    resourceId: null,
    fileName: null,
    filePath: null,
    fileType: null,
    fileSize: null,
    fileDesc: null,
    memberVip: null,
    chargeStatus: null,
    filePrice: null,
    fileStatus: null,
  },
  rules: {}
});

const {queryParams, form, rules} = toRefs(data);

/** 查询资源明细列表 */
function getList() {
  loading.value = true;
  queryParams.value.resourceId = props.resourceId;
  listSurResourceDetail(queryParams.value).then(response => {
    surResourceDetailList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    resourceId: null,
    fileName: null,
    filePath: null,
    fileType: null,
    fileSize: null,
    fileDesc: null,
    memberVip: null,
    chargeStatus: 0,
    filePrice: null,
    fileStatus: 0,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    delFlag: null
  };
  proxy.resetForm("surResourceDetailRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  form.value.resourceId = props.resourceId;
  title.value = "添加资源明细";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getSurResourceDetail(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改资源明细";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["surResourceDetailRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateSurResourceDetail(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSurResourceDetail(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除资源明细编号为"' + _ids + '"的数据项？').then(function () {
    return delSurResourceDetail(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('sources/surResourceDetail/export', {
    ...queryParams.value
  }, `surResourceDetail_${new Date().getTime()}.xlsx`)
}

/** 资源预览 */
function handleView(row) {
  // 获取预览临时鉴权码

}

// 获取文件名称
function getFileName(name) {
  // 如果是url那么取最后的名字 如果不是直接返回
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return name;
  }
}

function handleFileChange(files) {
  if (files && files[0]) {
    const file = files[0];
    if (file.rows) {
      form.value.fileName = getFileName(file.rows.fileName);
      form.value.fileSize = file.rows.fileSize;
    }
  }
}

function convertFileSize(size) {
  try {
    size = Number(size);
    let unitArr = ['B', 'KB', 'MB', 'GB', 'TB'];
    let count = 0;
    while (size > 1024) {
      count++;
      size = Number(size / 1024).toFixed(2);
    }
    return size + unitArr[count];
  } catch (e) {
    console.error(e);
  }
  return '-';
}

getList();
</script>
